package com.sdry.web.controller;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @ClassName: BaseController
 * @Description: t通用Controller
 * @Author cb
 * @Date 2018/4/24 11:43
 * @version 1.0
 */
@Controller
public abstract class BaseController {

    @InitBinder
    //此方法用于日期的转换，如果未加，当页面日期格式转换错误，将报400错误，实际是因为此方法
    public void initBinder(WebDataBinder binder) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 文件下载
     * @param response
     * @param url 文件路径（根路径）
     * @throws FileNotFoundException 文件存在异常
     */
    @RequestMapping("/downloadLocal")
    public void downloadLocal(HttpServletResponse response, String url) throws FileNotFoundException {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(url);
            // 取得文件名。
            String filename = file.getName();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(url));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }



}
